﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using Avalonia.Logging;
using Microsoft.Extensions.Hosting;

namespace alwitTest.YX
{
    internal class AsyncTimerService
    {
        private int m_timerCounter;

        public delegate void TimerTickEvent(int dataValue);
        public event TimerTickEvent TimerTickInvoke;

        private object m_criLock = new object();
        private bool m_timerEnabled = false;

        private object m_criLock_stop = new object();
        private bool m_timerStop = false;

        public AsyncTimerService(int timerCounter)
        {
            this.m_timerCounter = timerCounter;
        }

        public async void Start()
        {
            var _period = TimeSpan.FromMilliseconds(this.m_timerCounter);
            using var _timer = new PeriodicTimer(_period);
            while (await _timer.WaitForNextTickAsync())
            {
                if (TimerEnabled == true)
                {
                    TimerTickInvoke(0);
                }
                if (TimerStop == true)
                {
                    break;
                }
            }

            _timer.Dispose();
        
        }

        public void Stop()
        {
            TimerStop = true;
        }

        private bool TimerStop
        {
            get
            {
                lock (this.m_criLock_stop)
                {
                    return this.m_timerStop;
                }
            }
            set
            {
                lock (this.m_criLock_stop)
                {
                    this.m_timerStop = value;
                }
            }
        }

        internal bool TimerEnabled
        {
            get
            {
                lock(this.m_criLock)
                {
                    return this.m_timerEnabled;
                }
            }
            set
            {
                lock (this.m_criLock)
                {
                    this.m_timerEnabled = value;
                }
            }
        }

    }

}
